package syyrjx.jdbc.util;

import java.sql.*;
import java.util.ResourceBundle;

public class JDBCTool {
    static{
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            stmt = conn.createStatement();
            //人数
            String sql = "select count(username) from userinfo";
            rs = stmt.executeQuery(sql);
            rs.next();
            JDBCTool.count = rs.getInt(1);
            //题目数
            sql = "select count(question) from questioninfo";
            rs = stmt.executeQuery(sql);
            rs.next();
            JDBCTool.queCount = rs.getInt(1);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCClose(rs,stmt,conn);
        }
    }
    public static int count;
    public static int queCount;

    public static Connection getConnection() throws ClassNotFoundException,SQLException{
        ResourceBundle rb = ResourceBundle.getBundle("mysqlInfo");
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(rb.getString("url"), rb.getString("username"), rb.getString("password"));

    }

    public static void JDBCClose(ResultSet rs, Statement stmt, Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }



}
